package courier;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import entity.Comments;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.Orders;
import entity.Users;
import facade.CommentsFacadeLocal;
import facade.OrdersFacadeLocal;
import java.util.Date;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import utils.ConfigurationManager;

/**
 *
 * @author Andriy
 */
@ServletSecurity(
        @HttpConstraint(rolesAllowed = {"Administrator", "Courier"}))
public class courier extends HttpServlet {

    @EJB
    private CommentsFacadeLocal commentsFacade;
    @EJB
    private OrdersFacadeLocal ofl;
    private String orderDetail = ConfigurationManager.getInstance().getLinksProperties().getProperty("ORDER_DETAIL_PAGE");
    private String courierDashboardPage = ConfigurationManager.getInstance().getLinksProperties().getProperty("COURIER_DASHBOARD_PAGE");

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String sortBy = "idOrder";
            String by = "asc";
            String orderStatus = "shipped";
            int page = 1;
            
            if (request.getParameter("status") != null) {
                if (request.getParameter("status").equalsIgnoreCase("shipped")) {
                    orderStatus = request.getParameter("status");
                } else if (request.getParameter("status").equalsIgnoreCase("delivered")) {
                    orderStatus = request.getParameter("status");
                }
            }
            List<Orders> ord;
            if (request.getParameter("sort") != null) {
                if (request.getParameter("sort").equalsIgnoreCase("IdOrder")) {
                    sortBy = request.getParameter("sort");
                } else if (request.getParameter("sort").equalsIgnoreCase("orderDate")) {
                    sortBy = request.getParameter("sort");
                } else if (request.getParameter("sort").equalsIgnoreCase("idWarehouse")) {
                    sortBy = request.getParameter("sort");
                } else if (request.getParameter("sort").equalsIgnoreCase("address")) {
                    sortBy = request.getParameter("sort");
                } else if (request.getParameter("sort").equalsIgnoreCase("shippingPrice")) {
                    sortBy = request.getParameter("sort");
                } else if (request.getParameter("sort").equalsIgnoreCase("productPrice")) {
                    sortBy = request.getParameter("sort");
                }
            }
            if (request.getParameter("by") != null) {
                if (request.getParameter("by").equalsIgnoreCase("asc")) {
                    by = request.getParameter("by");
                } else if (request.getParameter("by").equalsIgnoreCase("desc")) {
                    by = request.getParameter("by");
                }
            }
            int numberOfPages = Math.round(ofl.count(orderStatus) / 15) + 1;
            if (request.getParameter("page") != null) {
                if (Integer.parseInt(request.getParameter("page")) < 1) {
                    page = 1;
                } else if (Integer.parseInt(request.getParameter("page")) > numberOfPages) {
                    page = numberOfPages;
                } else {
                    page = Integer.parseInt(request.getParameter("page"));
                }
            }
            ord = ofl.findRangeSortBy(page, orderStatus, sortBy, by);
            request.setAttribute("ordersList", ord);
            request.setAttribute("count", numberOfPages);
            request.setAttribute("sort", sortBy);
            request.setAttribute("by", by);
            request.setAttribute("page", page);
            request.setAttribute("status",orderStatus);
            RequestDispatcher dispatcher;
            dispatcher = getServletContext().getRequestDispatcher(courierDashboardPage);
            dispatcher.forward(request, response);
            /* TODO output your page here. You may use following sample code. */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            if (request.getParameter("idOrder") != null && request.getParameter("orderTrackNum") != null) {
                Orders order = ofl.find(Integer.parseInt(request.getParameter("idOrder")));
                if (order != null) {
                    if (request.getParameter("orderTrackNum").equalsIgnoreCase("" + order.getTrackingNumber())) {
                        if (ofl.setDelivered(Integer.parseInt(request.getParameter("idOrder"))) == 1) {
                            order.setOrderStatus("delivered");
                            request.setAttribute("success", "Successfully delivered");
                            String text = "SO transitioned to state delivered";
                            Users user = (Users) request.getSession().getAttribute("user");
                            Date date = new Date();

                            Comments comment = new Comments();
                            comment.setIdOrder(order);
                            comment.setCommentDate(date);
                            comment.setIdUser(user);
                            comment.setText(text);

                            commentsFacade.create(comment);
                            request.setAttribute("dashboard", 1);
                            request.setAttribute("order", order);
                            RequestDispatcher dispatcher;
                            dispatcher = getServletContext().getRequestDispatcher(orderDetail);
                            dispatcher.forward(request, response);
                        } else {
                            request.setAttribute("dashboard", 1);
                            request.setAttribute("order", order);
                            RequestDispatcher dispatcher;
                            dispatcher = getServletContext().getRequestDispatcher(orderDetail);
                            dispatcher.forward(request, response);
                        }
                    } else {
                        request.setAttribute("success", "Such order does not exist.");
                        doGet(request, response);
                    }
                } else {
                    request.setAttribute("success", "Such order does not exist.");
                    doGet(request, response);
                }
                //request.removeAttribute("idOrderDeliver");
            } else {
                request.setAttribute("success", "Such order does not exist.");
                doGet(request, response);

                //request.removeAttribute("idOrderDeliver");
            } /* TODO output your page here. You may use following sample code. */
        } finally {
            out.close();
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
